#include <QtCore>
#include <signal.h>

#include "RoRouter.h"
#include "RoServerModule.h"


void qApp_quit(int)
{
    qApp->quit();
}


int main(int argc, char * argv[])
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    QCoreApplication app(argc, argv);
    
    struct sigaction qApp_quit_sa;
    {
        qApp_quit_sa.sa_handler = qApp_quit;
        sigemptyset(&qApp_quit_sa.sa_mask);
        qApp_quit_sa.sa_flags = 0;
    }
    sigaction(SIGINT, &qApp_quit_sa, 0);
    sigaction(SIGHUP, &qApp_quit_sa, 0);
    sigaction(SIGTERM, &qApp_quit_sa, 0);

    QString runtimeDebugEnv = qgetenv("DEBUG").toLower();
    bool runtimeDebug = false;
    if ( not runtimeDebugEnv.isEmpty() )
    {
        if ( runtimeDebugEnv == "0" or
             runtimeDebugEnv == "false" or
             runtimeDebugEnv == "no" or
             runtimeDebugEnv == "off" )
        {
            runtimeDebug = false;
        }
        else
        {
            runtimeDebug = true;
        }
    }

    QPointer<RoServerModule> server = new RoServerModule(&app, runtimeDebug);
    QObject::connect(&app, SIGNAL( aboutToQuit() ),
                     server, SLOT( disconnectFromNetwork() ));

    server->connectToNetwork();
    if ( server->isConnected() )
        qDebug() << "Server is running on" << server->serverAddress() << ':' << server->serverPort();
    else
        qDebug() << "Server is NOT runnning:" << server->errorString();
    
    QPointer<RoRouter> router = new RoRouter(server);
    
    return app.exec();
}
